﻿import datetime

from django.shortcuts import render, redirect
from django.http import JsonResponse
from buyer import models
import hashlib
from seller import models as smodles


# Create your views here.

def pwd_md5(passwpord):
    # m = hashlib.md5()
    # m.update(passwpord.ecode)
    ret = hashlib.md5(passwpord.encode('utf-8')).hexdigest()
    return ret


from django.views import View


# CBV 基于类实现的视图
class Regiter(View):
    def get(self, request):
        return render(request, 'buyer/register.html')

    def post(self, request):
        name = request.POST.get('user_name')
        pwd = request.POST.get('user_pwd')
        cpwd = request.POST.get('user_cpwd')
        email = request.POST.get('user_email')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        if pwd == cpwd:
            user = models.User()
            user.name = name
            user.pwd = pwd_md5(pwd)
            user.email = email
            user.phone = phone
            user.address = address
            user.save()
            return redirect('/buyer/login/')
        else:
            msg = '两次密码不正确'
            return render(request, 'buyer/register.html', locals())


# 注册
def register(request):
    if request.method == 'POST':
        name = request.POST.get('user_name')
        pwd = request.POST.get('user_pwd')
        email = request.POST.get('user_email')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        user = models.User()
        user.name = name
        user.pwd = pwd_md5(pwd)
        user.email = email
        user.phone = phone
        user.address = address
        user.save()
        return redirect('/buyer/login/')
    return render(request, 'buyer/register.html')


# 判断是否被注册
def register_ajax(request):
    name = request.GET.get('username')
    print(name)
    user = models.User.objects.filter(name=name).first()
    if user:
        dic = {'msg': '用户名已被注册', 'code': '200'}
    else:
        dic = {'msg': '', 'code': '100'}
    return JsonResponse(dic)


# 登录功能
def login(request):
    msg = ''
    if request.method == 'POST':
        name = request.POST.get('user_name')
        pwd = request.POST.get('user_pwd')
        pwd = pwd_md5(pwd)
        print(name, pwd)
        user = models.User.objects.filter(name=name, pwd=pwd).first()
        if user:
            response = redirect('/buyer/index/')
            response.set_cookie('username', name)
            response.set_cookie('id', user.id)

            return response
        else:
            msg = '用户名或者密码错误'
    return render(request, 'buyer/login.html', {'msg': msg})


#   首页
def index(request):
    ####
    # name = request.COOKIES.get('username')
    # print(name)
    # if name:
    #     return render(request, 'buyer/index.html')
    # else:
    #     return redirect('/buyer/index/')
    goods_type_list = smodles.GoodsType.objects.all()
    # 2 . 轮播图放的商品
    lb_goods_list = smodles.Goods.objects.all().order_by('-id')[:4]
    goodslist = smodles.Goods.objects.all()
    for i in goods_type_list:
        goods_type = i
    return render(request, 'buyer/index.html', locals())


#  登出
def logout(request):
    response = redirect('/buyer/login/')
    response.delete_cookie('username')
    response.delete_cookie('id')
    return response


# 查看更多
def more_list_v3(request):
    # 获取商品的id
    goodstype_id = request.GET.get('goodstype_id')
    print(goodstype_id)
    # # goodsType = smodles.GoodsType.objects.get(id=goodstype_id)
    goods_list = smodles.Goods.objects.filter(goodsType=goodstype_id)
    # print(goods_list)

    return render(request, 'buyer/more_list_v4.html', locals())


#  给前端ajax传输数据
def ajax_more_goods_list_data(request):
    goodstype_id = request.GET.get('goodstype_id')
    print(goodstype_id)
    goods_list = smodles.Goods.objects.filter(goodsType_id=goodstype_id)
    print(goods_list)
    new_goods_list = []
    for goods in goods_list:
        dic = {}
        dic['id'] = goods.id
        dic['name'] = goods.name
        dic['img'] = goods.goodsimg.name
        dic['price'] = goods.price
        new_goods_list.append(dic)
    dic = {'msg': 'success', 'goodsList': new_goods_list}
    return JsonResponse(dic)


from rest_framework import generics
from buyer.serializers import GoodsSerializers


class GoodsListAPIViewAJAX(generics.ListAPIView):
    serializer_class = GoodsSerializers

    def get_queryset(self):
        goodstype_id = self.request.GET.get('goodstype_id')
        # print(goodstype_id)
        goods_list = smodles.Goods.objects.filter(goodsType_id=goodstype_id)
        return goods_list

    # 将图片的  绝对路径去掉   底层中的一些实现
    def get_serializer_context(self):
        return {
            'view': self
        }


#  展示细节
def goods_detail(request):
    id = request.GET.get('id')
    print(id)
    goods = smodles.Goods.objects.filter(id=id).first()
    new_goods_list = smodles.Goods.objects.all().order_by('-id')[:5]
    return render(request, 'buyer/detail.html', locals())


# 用户中心
def user_info_center(request):
    user_id = request.COOKIES.get('id')
    user = models.User.objects.filter(id=user_id).first()
    goods = smodles.Goods.objects.filter(id=user_id).first()
    # new_goods_list = modles.Cart.objects.all().order_by('-id')[:5]
    new_goods_list = models.Cart.objects.all().order_by('-id')[:4]
    address_obj_list = models.UserAddress.objects.all()
    buyer_id = request.COOKIES.get('id')
    orders_obj_list = models.Order.objects.filter(user_id=buyer_id)

    return render(request, 'buyer/user-center-info.html', locals())


# 添加收货地址
def buyer_address_add(request):
    buyer_id = request.COOKIES.get('id')
    if request.method == 'POST':
        # 获取表单内容
        shoujianren = request.POST.get('shoujianren')
        xiangxiaddress = request.POST.get('xiangxiaddress')
        youbian = request.POST.get('youbian')
        phone = request.POST.get('phone')

        address_obj = models.UserAddress()
        address_obj.name = shoujianren
        address_obj.detailadd = xiangxiaddress
        address_obj.youbian = youbian
        address_obj.phone = phone
        address_obj.user_id = buyer_id
        #  将之前的都改为false
        models.UserAddress.objects.filter(user_id=buyer_id).update(status=False)
        address_obj.status = True
        address_obj.save()

        return redirect('/buyer/user_info_center/')


# 修改状态
def change_address_status(request):
    buyer_id = request.COOKIES.get('id')
    id = request.GET.get('id')
    print(id)
    address_obj = models.UserAddress.objects.filter(id=id).first()
    # 通过ajax获取上地址id 根据id 查找那个地址那个地址被选中， 然后再把之前的所有status全部转化为false，
    models.UserAddress.objects.filter(user_id=buyer_id).update(status=False)
    # 把选中的地址设置成True  并且保存下来
    address_obj.status = True
    address_obj.save()
    return JsonResponse({'msg': 'ok'})


# 购物车
def shopping_car_list(request):
    user_id = request.COOKIES.get('id')
    print(user_id)
    cart_list = models.Cart.objects.filter(user_id=user_id)
    print(cart_list)
    return render(request, 'buyer/cart.html', locals())


# 添加东西到购物车
def shopping_car_add(request):
    user_id = request.COOKIES.get('id')
    if user_id:
        goods_id = request.GET.get('goods_id')
        print(goods_id)
        goods_number = request.GET.get('number')
        print(goods_number)
        goods = smodles.Goods.objects.filter(id=goods_id).first()
        # 当前用户的购物车
        cart_goods = models.Cart.objects.filter(goodsid=goods_id, user_id=user_id).first()
        # 如果存在修改它的数量
        if cart_goods:
            cart_goods.goodsnum += int(goods_number)
            cart_goods.save()
        else:
            goods_name = goods.name
            goods_price = goods.price
            goods_img = goods.goodsimg.name
            goods_num = goods_number
            cart = models.Cart()
            cart.name = goods_name
            cart.price = goods_price
            cart.goodsnum = goods_num
            cart.goodsimg = goods_img
            cart.user_id = user_id
            cart.goodsid = goods_id
            # cart.xiaoji = goods_xiaoji
            cart.save()
        dic = {'code': 1000, 'msg': '添加成功...'}
    else:
        dic = {'msg': '200', 'msg': '请登录....'}
    return JsonResponse(dic)


# 增加商品数量
def add_car_num(request):
    id = request.GET.get('car_id')
    cart_goods = models.Cart.objects.filter(id=id).first()
    print(id)
    print(cart_goods)
    cart_goods.goodsnum += 1
    cart_goods.save()
    return JsonResponse({'msg': 'ok'})


# 减少商品数量
def reduce_car_num(request):
    id = request.GET.get('car_id')
    cart_goods = models.Cart.objects.get(id=id)
    cart_goods.goodsnum -= 1
    cart_goods.save()
    return JsonResponse({'msg': 'ok'})


#  删除购物车商品
def shopping_car_delete(request):
    goods_id = request.GET.get('id')
    print(goods_id)
    cart_goods = models.Cart.objects.filter(id=goods_id).first()
    img = cart_goods.goodsimg
    # img.delete()

    cart_goods.delete()
    return redirect('/buyer/shopping_car_list/')


# 我的订单
def my_orders(request):
    buyer_id = request.COOKIES.get('id')
    orders_obj_list = models.Order.objects.filter(user_id=buyer_id)
    for orders_obj in orders_obj_list:
        if orders_obj.orderaddress == '':
            address_obj = models.UserAddress.objects.filter(user_id=buyer_id, status=True).first()
            orders_obj.orderaddress = address_obj.detailadd + '(' + address_obj.name + '收)' + address_obj.phone
            orders_obj.save()
    return render(request, 'buyer/myorders.html', locals())


# 立即购买
def now_buy(request):
    buyer_id = request.COOKIES.get('id')
    goodsid = request.GET.get('goodsid')
    print(goodsid)
    number = request.GET.get('number')
    print(number)
    # 生成订单
    orders_obj = models.Order()
    orders_obj.orderno = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ('%04d' % int(buyer_id))
    orders_obj.ordertime = datetime.datetime.now()
    orders_obj.ordertotal = ''
    # 查询当前用户选中的id
    address = models.UserAddress.objects.filter(user_id=buyer_id, status=True).first()
    # 判断是否有地址
    if address:
        orders_obj.orderaddress = address.detailadd + '(' + address.name + '收)' + address.phone
    else:
        orders_obj.orderaddress = ''
    orders_obj.user_id = buyer_id
    orders_obj.save()
    # 订单详情
    goods_obj = smodles.Goods.objects.get(id=goodsid)
    print(goods_obj)
    orders_obj_detail = models.OrderDetails()
    orders_obj_detail.goodsname = goods_obj.name
    orders_obj_detail.goodsprice = goods_obj.price
    orders_obj_detail.goodsnum = number
    orders_obj_detail.goodsimg = goods_obj.goodsimg.name
    orders_obj_detail.goodsxiaoji = goods_obj.price * int(number)
    orders_obj_detail.order = orders_obj
    orders_obj_detail.save()
    # 总价
    total = goods_obj.price * int(number)
    orders_obj.ordertotal = total
    orders_obj.save()
    return render(request, 'buyer/place_order.html', locals())


# 结算
def orders_list(request):
    buyer_id = request.COOKIES.get('id')
    # 获取购物车 id
    # 用getlist 获取多个checkbox的多个值
    shoppingcarids = request.POST.getlist('shoppingcarids')
    # print(shoppingcarids)
    orders_obj = models.Order()
    orders_obj.orderno = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ('%04d' % int(buyer_id))
    orders_obj.ordertime = datetime.datetime.now()
    orders_obj.ordertotal = ''
    # 查询当前用户选中的id
    address = models.UserAddress.objects.filter(user_id=buyer_id, status=True).first()
    # 判断是否有地址
    if address:
        orders_obj.orderaddress = address.detailadd + '(' + address.name + '收)' + address.phone
    else:
        orders_obj.orderaddress = ''
    orders_obj.user_id = buyer_id
    orders_obj.save()
    # 生成订单详情
    total = 0
    for cartid in shoppingcarids:
        cart_obj = models.Cart.objects.get(id=cartid)
        order_detail_obj = models.OrderDetails()
        order_detail_obj.goodsname = cart_obj.name
        order_detail_obj.goodsprice = cart_obj.price
        order_detail_obj.goodsnum = cart_obj.goodsnum
        order_detail_obj.goodsimg = cart_obj.goodsimg
        order_detail_obj.goodsxiaoji = cart_obj.goodsnum * float(cart_obj.price)
        order_detail_obj.order = orders_obj
        order_detail_obj.save()
        total += order_detail_obj.goodsxiaoji
        cart_obj.delete()
    # 给商品总价赋值
    orders_obj.ordertotal = total
    orders_obj.save()

    return render(request, 'buyer/place_order.html', locals())
    # 用户id
    # buyer_id = request.COOKIES.get('id')
    # orders = models.Order()
    # orders.user_id = buyer_id
    # orders.orderno = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f') + ('%04d' % int(buyer_id))
    # orders.ordertime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # print(orders.orderno, orders.ordertime)
    # orders.user_id = buyer_id
    # orders.ordertotal = 88
    # address = models.UserAddress.objects.filter(user_id=buyer_id,status=True).first()
    # orders.orderaddress = address.detailadd
    # orders.save()
    # address_obj = models.UserAddress.objects.filter(user_id=buyer_id, status=True)
    # cart_goods_list = models.Cart.objects.filter(user_id=buyer_id)
    # # print(cart_goods_list)
    # count = 0
    # for goods in cart_goods_list:
    #     order_datails = models.OrderDetails()
    #     if orders:
    #         orders = models.Order.objects.filter(user_id=buyer_id).first()
    #
    #         print(orders.orderaddress)
    #         order_datails_list = models.OrderDetails.objects.filter(order_id=buyer_id)
    #         return render(request,'buyer/place_order.html',locals())
    #     else:
    #         order_datails.goodsname = goods.name
    #         order_datails.goodsprice = goods.price
    #         order_datails.goodsnum = goods.goodsnum
    #         order_datails.goodsimg = goods.goodsimg
    #         order_datails.goodsxiaoji = float(order_datails.goodsnum) * float(order_datails.goodsprice)
    #         # print(order_datails.goodsxiaoji)
    #         order_datails.order_id = orders.id
    #         # print(order_datails.order_id)
    #         order_datails.save()
    #     count += goods.goodsnum


from alipay import AliPay


# from alipay.utils import AliPayConfig


def zfb(request):
    # 获取订单号
    ordernum = request.GET.get('orderno')
    ordertotal = request.GET.get('total')

    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
    MIIEowIBAAKCAQEAg4juzvWYE2Oy87nq5OSpOx96MBHS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pGB+b+fGL5HVEHw03FOnKg2CldQalID170C7nXHD5zylg7nhWayk0So1EVzYL80lJ+bS+76KRcDyDFV0GnIjRQkZsgP38kO8n7mz7G5hxYRpwKBgGdESRKGpsk8bfOs/2kSXzLd9BKn0waVWSnNKmwzLW0ck+y5MMnUGU7e+iXQbZhn+JSyu9nRKrshF6o1iXd5zti5DgTVlv7TPUmQTI2hEOnxU+MovQ6+jKb4tf5U0txY7QYCSVyN/kJCNMkSzMv414GSvP5/KUfUGk4XjPyIDmZhAoGBAIzEdm/NZGjB/ggw7zXvjHny9pwN13weOYFXFaF849NvJDM5YyI5i4AXl5bJqwZZ2s+sW5cZEloMimc2sQO9hRcoSljXmIoT2R4rOvYCmYNPCXU7b/k+BDtvnK+SE3hfNjogNBoF3dm7ft6I17qNnNB05QD+ZN5a+f7gSRCFVmps
    -----END RSA PRIVATE KEY-----"""

    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn0wLJGuNWBCvReDGk2NROkfC3jpC3uEjn8gTcw1yCMUhn1pc67LIneqaG1J/eqB19pG/lKs/QDuZ/nDxtllmRtMpykHQ2uLfM97ToXYjJaKDRrNaxdU25HbVwA4S2z34zdoO2Am+hZ8bDa8eCpek4KdvJb+SLT66MsZQZJU1IuG5zp9BBDVoc5IC3zNxHiBdCzTiUujq/H8mdjlj0Gj46cWAA6HF9rpSzwlL9+ddnv5WQtC4U9SsgVEFHwZVOvQUpi84Iot+/C1i/MiJnObAtOLT6UqtrVCPjvXKiD03c2Rpyoopi+7w6nGlvyJYcaJ51f0gWKigeC/BEce5EGcoowIDAQAB
    -----END PUBLIC KEY-----"""

    alipay = AliPay(
        appid="2021000118662432",
        app_notify_url=None,
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",
        debug=False,
        verbose=False,
    )
    subject = '天天生鲜订单'
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=ordernum,
        total_amount=ordertotal,
        subject=subject,
        return_url="http://127.0.0.1:8000/buyer/update_orders_status/?orderno=" + ordernum,
        notify_url="https://example.com/notify"
    )

    url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
    return redirect(url)


# 支付成功之后返回
def update_orders_status(request):
    orderno = request.GET.get('orderno')
    order_obj = models.Order.objects.get(orderno=orderno)
    order_obj.orderstatus = True
    order_obj.save()
    return redirect('/buyer/my_orders/')


###########################################################################################
from django.views import View
from django.shortcuts import HttpResponse


#  视图类
class CBVtest(View):
    # 编写方法 当前段使用get  会自动执行
    def get(self, request):
        return render(request, 'buyer/cbvtest.html')
        pass

    def post(self, request):
        username = request.POST.get('username')
        print(username)
        return HttpResponse('post')


from rest_framework.views import APIView
from buyer.serializers import GoodsSerializers
from rest_framework.response import Response


class GoodsAPIView(APIView):
    def get(self, request):
        goodstype_id = request.GET.get('goodstype_id')
        print(goodstype_id)
        goods_list = smodles.Goods.objects.filter(goodsType_id=goodstype_id)
        # 使用序列化器对goodslist进行json转换
        ret = GoodsSerializers(goods_list, many=True)  # 可以换换为列表many=True
        print(ret)
        # 返回json数据 导包 response
        return Response(ret.data)


#  3.
from rest_framework import generics, mixins


class GoodsGenericView(generics.GenericAPIView, mixins.ListModelMixin):
    # 复写方法
    serializer_class = GoodsSerializers

    def get_queryset(self):
        goodstype_id = self.request.GET.get('goodstype_id')
        # print(goodstype_id)
        goods_list = smodles.Goods.objects.filter(goodsType_id=goodstype_id)
        return goods_list

    def get(self, request):
        return self.list(request)


# 继承ListAPIView  底层实现  直接继承了 以上的两个类，并且变写了get方法  不用去调用以上的def get 方法了

class GoodsListAPIView(generics.ListAPIView):
    serializer_class = GoodsSerializers

    def get_queryset(self):
        goodstype_id = self.request.GET.get('goodstype_id')
        # print(goodstype_id)
        goods_list = smodles.Goods.objects.filter(goodsType_id=goodstype_id)
        return goods_list


#  继承 viewset
from rest_framework import viewsets


class GoodsViewset(viewsets.ModelViewSet):
    serializer_class = GoodsSerializers

    def get_queryset(self):
        goodstype_id = self.request.GET.get('goodstype_id')
        # print(goodstype_id)
        goods_list = smodles.Goods.objects.filter(goodsType_id=goodstype_id)
        return goods_list
